<!-- Dashboard -->
<template>
  <el-container class="dashboard">
    <el-header class="header">
      <div class="logo-box">
        <a href="javascript:void(0)" @click="goDashboard()">
          <img src="@/assets/home/logo.png" alt="" />
        </a>
      </div>

      <div class="page-name">{{ $t($route.meta.title) }}</div>

      <div class="user-info" v-if="user">
        <el-dropdown @command="dropMenuEvt">
          <span class="el-dropdown-link">
            {{ user.name }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="changePassword">
              修改密码
            </el-dropdown-item>
            <el-dropdown-item command="logOut"> 安全退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-header>
    <el-container class="content">
      <el-aside width="200px" class="left">
        <el-menu :default-active="defaultActive" router unique-opened>
          <template v-for="item in activeMenus">
            <el-submenu
              v-if="item.children.length > 0"
              :index="item.key"
              :key="item.key"
            >
              <template slot="title">
                <i class="iconfont" :class="item.icon"></i>
                {{ $t(item.name) }}
              </template>
              <!-- 二级菜单 -->
              <el-menu-item
                v-for="child in item.children"
                :index="child.key"
                :key="child.key"
              >
                {{ $t(child.name) }}
              </el-menu-item>
            </el-submenu>

            <el-menu-item
              class="menu-item"
              v-else
              :index="item.key"
              :key="item.key"
            >
              <template slot="title">
                <i class="iconfont" :class="item.icon"></i>
                {{ $t(item.name) }}
              </template>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      <el-main class="right">
        <router-view class="page-main-body-box"></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Menus from "@/js/menus.js";
import { mapState, mapMutations } from "vuex";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      token: localStorage.getItem("admin-token"),
      menus: Menus,
      defaultActive: "/dashboard",
    };
  },
  //监听属性 类似于data概念
  computed: {
    ...mapState(["user"]),

    activeMenus: function () {
      let menus = [];
      if (!this.user) {
        return menus;
      }

      for (let i = 0; i < Menus.length; i++) {
        // 1. 只有一级菜单情况下，直接添加，不做权限判断
        let menuItem = Menus[i];
        if (menuItem.children.length === 0) {
          menus.push(menuItem);
        } else {
          // 默认情况下，子节点没有过滤前，空的
          let children = [];
          // 对子节点进行过滤
          for (let j = 0; j < menuItem.children.length; j++) {
            // 判断是否超级管理员
            if (this.user.is_super) {
              if (menuItem.children[j].permission === "super-slug") {
                children.push(menuItem.children[j]);
                continue;
              }
            }
            if (
              this.user.permissions &&
              this.user.permissions[menuItem.children[j].permission] !=
                undefined
            ) {
              children.push(menuItem.children[j]);
            }
          }
          // console.log(children);
          if (children.length != 0) {
            // console.log(children);
            // 修改menuItem 有权限项目，现在children就是过滤过的项
            menuItem.children = children;
            menus.push(menuItem);
          }
        }
      }
      return menus;
    },
  },
  //监控data中的数据变化
  watch: {
    $route: {
      deep: true,
      immediate: true,
      handler: function (newValue) {
        if (newValue.meta.is_defaultActive) {
          this.defaultActive = newValue.meta.is_defaultActive;
        } else {
          this.defaultActive = newValue.name;
        }
        this.defaultActive = "/" + this.defaultActive;
      },
    },
  },
  //方法集合
  methods: {
    ...mapMutations(["loginHandle", "logOut"]),
    menuSelect(path) {
      if (this.$route.name === path) {
        // 已经是当前页面
        return;
      }
      this.$router.push({ name: path });
    },
    dropMenuEvt(cmd) {
      if (cmd === "logOut") {
        this.logoutEvt();
      } else if (cmd === "changePassword") {
        this.changePassword();
      }
    },

    logoutEvt() {
      this.$request
        .post("logout")
        .then(() => {
          this.logOut();
          this.$message.success(this.$t("common.success"));
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },

    changePassword() {
      this.$router.push({ name: "AdministratorChangePassword" });
    },
    logOut() {
      localStorage.clear();
      this.$router.push({ path: "/" });
    },
    goDashboard() {
      if (this.$route.name !== "Dashboard") {
        this.$router.push({ path: "/dashboard" });
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.$request.get("user").then((res) => {
      this.loginHandle(res.data);
    });
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='less' scoped>
.el-dropdown-menu {
  top: 37px !important;
  right: 30px !important;
  left: auto !important;
}
.dashboard {
  .header {
    height: 56px !important;
    padding: 0;
    background: #fff;
    text-align: center;
    color: #333;
    display: flex;
    justify-content: space-between;
    .logo-box {
      margin-left: 44px;
      margin-right: 44px;
      padding-top: 24px;
      img {
        width: 112px;
        height: 30px;
      }
    }
    .page-name {
      flex: 1;
      padding-left: 30px;
      font-size: 20px;
      font-weight: 600;
      color: #333;
      line-height: 56px;
      text-align: left;
    }
    .user-info {
      width: auto;
      padding-right: 30px;
      line-height: 56px;
      span {
        cursor: pointer;
      }
    }
  }
  .content {
    position: relative;
    display: flex;
    justify-content: space-between;
    .left {
      height: calc(100vh - 56px);
      box-sizing: border-box;
      width: 200px;
      background: #fff;
      padding-top: 24px;
      overflow-x: hidden;
      overflow-y: auto;
    }
    .el-main.right {
      height: calc(100vh - 56px);
      box-sizing: border-box;
      background: #f1f2f9;
      padding: 20px 5px 20px 20px !important;
      overflow: auto;
    }
  }
}

.el-submenu,
.is-active {
  width: 200px;
  .el-menu-item {
    padding-left: 74px !important;
    a {
      display: block;
      width: 100%;
      height: 100%;
      color: #303133;
    }
  }
}
.el-menu-item.is-active {
  color: #fff;
  background-color: #409eff;
  a {
    color: #fff;
  }
}
.el-col-12 {
  width: 100% !important;
}
.iconfont {
  font-size: 24px;
  margin-right: 12px;
  color: #556;
}
.el-menu {
  border: 0 !important;
}
.page-main-body-box {
  overflow-y: auto;
}
</style>